package org.activequant.data.retrieval.ib;

import java.util.Calendar;

import org.activequant.core.domainmodel.SeriesSpecification;
import org.activequant.core.domainmodel.data.QuoteSeries;
import org.activequant.core.types.TimeStamp;
import org.activequant.data.annotations.Vendor;
import org.activequant.data.retrieval.IQuoteSeriesSource;
import org.activequant.util.ib.IBTwsConnection;
import org.apache.log4j.Logger;

/**
* 
* abstracted Interactive Broker Quote series source, requires a properly configured
* monitor. <br>
* IBQuoteSeriesSource implements IQuoteSeriesSource. Holds the following associated variable:
* <ul>
* <li>monitor(IBTwsConnection)</li>
* </ul>
* <b>History:</b><br>
*  - [24.06.2007] Created (Ulrich Staudinger)<br>
*  - [11.08.2007] Added array functions (Erik Nijkamp)<br>
*  - [14.08.2007] removing symbol code, extending from CandleSeriesSourceBase. (Ulrich Staudinger)<br>
*  - [20.01.2008] Removed getVendor(), added annotation, removed main() (Erik Nijkamp)<br>
*  - [05.05.2008] eXtracting constants for data types (Ulrich Staudinger)<br>
*
*  @author Ulrich Staudinger
*  @author Erik Nijkamp
*/
@Vendor("IB")
public class IBQuoteSeriesSource implements IQuoteSeriesSource {
	/**
	 * private IBTwsConnection monitor;
	 */
	private IBTwsConnection monitor;

	protected final static Logger log = Logger.getLogger(IBQuoteSeriesSource.class);
	/**
	 * constructs an IBCandleSeriesSource(implements ICandleSeriesSource) using the given monitor(IBTwsConnection) to set its associated monitor(IBTwsConnection)
	 * @param monitor
	 */
	public IBQuoteSeriesSource(IBTwsConnection monitor) {
		this.monitor = monitor;
	}

	/**
	 * returns a QuoteSeries for the given query(SeriesSpecification) (by fetching historical data from IB)<br/>
	 * Requests BID_ASK instead of the default TRADES data points,<br>
	 */
	public QuoteSeries fetch(SeriesSpecification query) throws Exception {
		
		if(query.getTimeFrame() == null) {
			throw new NullPointerException("timeFrame");
		}

		TimeStamp startDate = query.getStartTimeStamp();
		TimeStamp endDate = query.getEndTimeStamp();
		
		if(endDate == null) {
			log.warn("end date not specified: assuming now");
			endDate = new TimeStamp();
		}
		
		if(startDate == null) {
			log.warn("start date not specified: assuming 1 day before end");
			Calendar cal = Calendar.getInstance();
			cal.setTime(endDate.getDate());
			cal.add(Calendar.DAY_OF_YEAR, -1);
			startDate = new TimeStamp(cal.getTime());
		}
		
		String type = IBTwsConnection.TRADES;
		if(query.getInstrumentSpecification().containsDecoration(IBTwsConnection.DATA_TYPE)){
			type = query.getInstrumentSpecification().getDecoration(IBTwsConnection.DATA_TYPE);
		}
		
		String barSize = IBTwsConnection.timeFrameToBarSize(query.getTimeFrame());
		return monitor.fetchQuotes(startDate, endDate, barSize, type, query);
	}
}
